package com.thinkingstar.iads.common.filter;

import org.nutz.mvc.View;
import java.util.Hashtable;
import org.nutz.lang.Strings;
import org.nutz.mvc.ActionFilter;
import org.nutz.mvc.view.RawView;
import org.nutz.mvc.ActionContext;
import org.apache.commons.lang3.StringUtils;
import org.nutz.mvc.view.ServerRedirectView;

import com.thinkingstar.iads.common.config.Globals;
import com.thinkingstar.iads.cs.sys.entity.SysUser;


/**
 *
 */
public class UserLoginFilter implements ActionFilter {

	public View match(ActionContext context) {
		SysUser user = (SysUser) context.getRequest().getSession()
				.getAttribute("userSession");
        String contentType=context.getRequest().getContentType();
        if(Strings.sNull(contentType).contains("application/x-www-form-urlencoded")&&user==null){
            context.getResponse().setHeader("sessionstatus","timeout");
            return new RawView("");
        }else if (user == null) {
			ServerRedirectView view = new ServerRedirectView(
					"/login");
			return view;
		}
		
		Hashtable<String, String> btnmap= user.getBtnmap();
		if(btnmap!=null){
			String initBtn="";
			String bts=btnmap.get(Strings.sNull(context.getRequest().getRequestURI().replace(Globals.APP_BASE_NAME, "")));
			if(bts!=null&&bts.indexOf(",")>0){
				String[] tb= StringUtils.split(bts,",");
				for(int i=0;i<tb.length;i++){
					initBtn+="$Z(\""+tb[i]+"\").enable();\r\n"; 
				}
				
			} 
			context.getRequest().setAttribute("initBtn", initBtn);
		}
		context.getRequest().setAttribute("curuser", user);
		return null;
	}
	
	
	
	

}
